package com.hk.service.order.impl;

import com.hk.commons.*;
import com.hk.commons.utils.MsgTypeConstants;
import com.hk.service.IPush;
import com.hk.service.sys.IAnswer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.hk.commons.entity.product.Payment;
import com.hk.commons.entity.sys.SysUser;
import com.hk.commons.message.PaymentMsg;
import com.hk.dao.base.impl.BaseServiceImpl;
import com.hk.service.order.IPayment;
import com.hk.service.sys.ISysUser;

import java.util.List;
import java.util.Map;

@Service
public class PaymentImpl extends BaseServiceImpl<Payment> implements IPayment {

	private Logger logger = LoggerFactory.getLogger(PaymentImpl.class);

	@Autowired
	private ISysUser userService;

	@Autowired
	private IPush pushService;

	@Autowired
	private JdbcTemplate jdbcTemplate;

	@Autowired
	private IAnswer answerService;

	@Override
	public Payment findById(long id) {
		return getById(id);
	}

	@Override
	public Long add(Payment model) {
		Long id = null;
		if (model != null && model.getPaymentNo() != null) {
			id = LongId.get();
			model.setId(id);
			model.setCts(System.currentTimeMillis());
			if (StringHelper.isNotEmpty(model.getAccountName())) {
				model.setAccountName(model.getAccountName().trim());
			} else if (model.getUserId() != null) {
				SysUser user = userService.findById(model.getUserId());
				if (user != null && StringHelper.isNotEmpty(user.getRealName())) {
					model.setAccountName(user.getRealName());
				}

			}
			if (StringHelper.isNotEmpty(model.getIdentityNo())) {
				model.setIdentityNo(model.getIdentityNo().toUpperCase());
			}
			model.setPaymentNo(model.getPaymentNo().trim());
			super.save(model);
			logger.info("add result true new Id = " + id);


			//新绑卡用户更新用户的投资确认函
			if(answerService.checkByUserId(model.getUserId())){
				answerService.updKycUrl(model.getUserId());
				logger.info("will start to update user kycurl after update payment");
			}



			SysUser user = this.userService.findById(model.getUserId());
			String message = String.format("恭喜您，绑卡成功！请在我的-我的银行卡中进行查看");
			this.pushService.jgPushCustomerMsg(message, "绑卡成功", null, null, null, user.getName(), ConstantPush.PUSH_MENU, MsgTypeConstants.BIND_CARD);
		}

		try {
			if(model != null && getPaymentMsg(model) != null) {
				RedisCilent.listSet(CacheConstants.FINALCIAL_PUSH,
						JsonUtils.toJson(getPaymentMsg(model)));
			}
			} catch (Exception e) {
			logger.error("error" ,e);
		}







		return id;
	}

	private PaymentMsg getPaymentMsg(Payment payment) {
		PaymentMsg paymentMsg = new PaymentMsg();
		paymentMsg.setUserId(payment.getUserId());
		paymentMsg.setAccountName(payment.getAccountName());
		return paymentMsg;
	}

	@Override
	public Payment getByUserId(Long userId) {
		HqlFilter hqlFilter = new HqlFilter();
		hqlFilter.addEQFilter("userId", userId);
		hqlFilter.addSql(" and cardStatus in ("
				+ CardStatusCode.PAYMENT_DISPLAY_SHOW + ","
				+ CardStatusCode.FY_CHANGE_CARD_FAIL + ","
				+ CardStatusCode.FY_CHANGE_CARDING + ")");
		// hqlFilter.addEQFilter("cardStatus", 1);
		hqlFilter.addSort("cts");
		return getByFilter(hqlFilter);

	}

	@Override
	public Payment getHuoChaiUserId(Long userId) {
		HqlFilter hqlFilter = new HqlFilter();
		hqlFilter.addEQFilter("userId", userId);
		hqlFilter.addEQFilter("cardStatus", 1);
		hqlFilter.addSort("cts");
		hqlFilter.addOrder("desc");
		return getByFilter(hqlFilter);
	}

	@Override
	public Payment getByPaymentNo(String paymentNo) {
		Payment payment = null;
		if (StringHelper.isNotEmpty(paymentNo)) {
			HqlFilter hqlFilter = new HqlFilter();
			hqlFilter.addEQFilter("paymentNo", paymentNo);
			payment = getByFilter(hqlFilter);
		}
		return payment;
	}

	@Override
	public Boolean isSame(Payment a, Payment b) {
		Boolean result = false;

		if (a != null && b != null && a.getUserId().equals(b.getUserId())
				&& a.getPaymentNo().equals(b.getPaymentNo())
				&& a.getPhone().equals(b.getPhone())
				&& a.getUserId().equals(b.getUserId())) {
			result = true;
		}
		logger.info("isSame result = " + result);
		return result;
	}

	@Override
	public Boolean existById(Long id) {

		Payment payment = getById(id);

		return payment != null;
	}

	/**
	 * 检查支付方式是否相同
	 * 
	 * @param pay01
	 * @param pay02
	 * @return
	 */
	@Override
	public Boolean checkSamePayment(Payment pay01, Payment pay02) {
		Boolean result = false;
		// 如果订单的支付信息id不为空
		if (pay01 == null || pay02 == null) {
			return false;
		}

		if (checkFullMsg(pay01) && checkFullMsg(pay01)) {
			if (pay01.getAccountName().equalsIgnoreCase(pay02.getAccountName())
					&& pay01.getPaymentNo().equalsIgnoreCase(
							pay02.getPaymentNo())
					&& pay01.getIdentityNo().equalsIgnoreCase(
							pay02.getIdentityNo())
					&& pay01.getPhone().equalsIgnoreCase(pay02.getPhone())) {

				result = true;
			} else {
				result = false;
			}
		} else {
			result = false;
		}
		logger.info("checkSamePayment result = " + result);
		return result;
	}

	@Override
	public Boolean checkFullMsg(Payment pay) {

		Boolean result = true;

		if (pay == null) {
			return false;
		}

		if (StringHelper.isEmpty(pay.getAccountName())
				|| StringHelper.isEmpty(pay.getPhone())
				|| StringHelper.isEmpty(pay.getIdentityNo())
				|| StringHelper.isEmpty(pay.getPaymentNo())) {

			logger.info("checkFullMsg failed : accountName = "
					+ pay.getAccountName() + "  phone = " + pay.getPhone()
					+ "  identityNo = " + pay.getIdentityNo()
					+ "  paymentNo = " + pay.getPaymentNo());
			result = false;
		}
		return result;
	}

	@Override
	public Long add(Payment u, Integer companyId) {
		u.setSupportCompany(getCompanyInfo(companyId));
		Long id = this.add(u);
		return id;
	}

	private String getCompanyInfo(Integer companyId) {
		return "-" + companyId + "-";
	}

	@Override
	public void setAddCardCompany(Integer company, Payment payment) {
		String surpportCompany = payment.getSupportCompany();

		if (StringHelper.isEmpty(surpportCompany)) {
			surpportCompany = CardStatusCode.NEVER_BIND_CARD + ","
					+ CardStatusCode.NEVER_BIND_CARD + ","
					+ CardStatusCode.NEVER_BIND_CARD;
		}

		String[] companies = surpportCompany.split(",");
		switch (company) {
		case ConstantRoute.COMPANY_HUAKANG:
			surpportCompany = ConstantRoute.COMPANY_HUAKANG + ","
					+ companies[1] + "," + companies[2];
			break;
		case ConstantRoute.COMPANY_HUOCHAI:
			surpportCompany = companies[0] + ","
					+ ConstantRoute.COMPANY_HUOCHAI + "," + companies[2];
			break;
		case ConstantRoute.COMPANY_YINGMI:
			surpportCompany = companies[0] + "," + companies[1] + ","
					+ ConstantRoute.COMPANY_YINGMI;
			break;
		default:
			break;
		}

		payment.setSupportCompany(surpportCompany);
		logger.info("当前卡号设置绑卡公司为：surpportCompany={}", surpportCompany);
	}

	@Override
	public String getCardCompany(Integer company, Payment payment) {
		String resultCompany = "";
		String supportCompanys = payment.getSupportCompany();// 1，3，4代表三家公司富友、火柴、盈米
		if (StringHelper.isNotEmpty(supportCompanys)) {
			String[] companys = supportCompanys.split(",");
			switch (company) {
			case ConstantRoute.COMPANY_HUAKANG:
				resultCompany = companys[0];
				break;
			case ConstantRoute.COMPANY_HUOCHAI:
				resultCompany = companys[1];
				break;
			case ConstantRoute.COMPANY_YINGMI:
				resultCompany = companys[2];
				break;
			default:
				break;
			}
		}
		return resultCompany;
	}

	@Override
	public void changeCardStatus(Integer company, Payment payment,
			Integer cardStatus) {
		String surpportCompany = payment.getSupportCompany();
		if (StringHelper.isEmpty(surpportCompany)) {
			surpportCompany = CardStatusCode.NEVER_BIND_CARD + ","
					+ CardStatusCode.NEVER_BIND_CARD + ","
					+ CardStatusCode.NEVER_BIND_CARD;
		}
		String[] companies = surpportCompany.split(",");
		switch (company) {
		case ConstantRoute.COMPANY_HUAKANG:
			surpportCompany = cardStatus + "," + companies[1] + ","
					+ companies[2];
			break;
		case ConstantRoute.COMPANY_HUOCHAI:
			surpportCompany = companies[0] + "," + cardStatus + ","
					+ companies[2];
			break;
		case ConstantRoute.COMPANY_YINGMI:
			surpportCompany = companies[0] + "," + companies[1] + ","
					+ cardStatus;
			break;
		default:
			break;
		}

		payment.setSupportCompany(surpportCompany);
		logger.info("当前卡号更改绑卡渠道为：surpportCompany={}", surpportCompany);
	}


	@Override
	public Payment getPaymentInfo(Long userId, Long paymentId) {
		Payment payment = null;

		//富有支付
		if(paymentId.toString().equals(ConstantPayment.FYJZH_PAY)){
			String sql = "select * from t_payment where userId = ? and cardStatus = 1 and supportCompany like \"1%\"";
			List<Map<String, Object>> list = this.jdbcTemplate.queryForList(sql, new Object[] {
					userId
			});
			payment = listToPayment(list);

			if (payment == null) {
				sql = "select * from t_payment where userId = ? and cardStatus = -200 and supportCompany like \"1%\"";
				list = this.jdbcTemplate.queryForList(sql, new Object[] {
						userId
				});
				payment = listToPayment(list);
			}
		}else{
			//非富有支付
			payment = this.findById(paymentId);
		}
		return payment;
	}

	private Payment listToPayment(List<Map<String, Object>> list) {
		Payment payment = null;

		if (list != null && list.size() > 0) {
			Map<String, Object> map = list.get(0);
			payment = new Payment();

			if (map.get("accountName") != null) {
				payment.setAccountName((String)map.get("accountName"));
			}

			if (map.get("identityNo") != null) {
				payment.setIdentityNo((String)map.get("identityNo"));
			}


			if (map.get("paymentNo") != null) {
				payment.setPaymentNo((String)map.get("paymentNo"));
			}

			if (map.get("bankName") != null) {
				payment.setBankName((String)map.get("bankName"));
			}

		}
		return payment;
	}


	@Override
	public Payment getIfaPayment(Long userId) {
		HqlFilter hqlFilter = new HqlFilter();
		hqlFilter.addEQFilter("userId", userId);
		hqlFilter.addSql(" and cardStatus in ("
				+ CardStatusCode.PAYMENT_DISPLAY_SHOW + ","
				+ CardStatusCode.FY_CHANGE_CARD_FAIL + ","
				+ CardStatusCode.FY_CHANGE_CARDING + ")");
		hqlFilter.addSort("cts");
		List<Payment> paymentList = this.findByFilter(hqlFilter);


		if(paymentList == null || paymentList.size() == 0){
			return null;
		}

		logger.info("总绑卡条数为={}", paymentList.size());

		for(Payment payment : paymentList){
			String supportCompany = payment.getSupportCompany();
			String[] companies = supportCompany.split(",");
			logger.info("supportCompany = {} ", supportCompany);
			String company = companies[0];
			logger.info("suppont company 0 = {}", company);
			if(company.equals(String.valueOf(ConstantRoute.COMPANY_HUAKANG))){
				logger.info("查到绑卡数据，将返回 paymentId={}, paymentNo={}", payment.getId(), payment.getPaymentNo());
				return  payment;
			}
		}

		return paymentList.get(0);
	}

	@Override
	public void ChangeAllCardStatus(Long userId, Integer status) {
		StringBuilder sql = new StringBuilder();
		sql.append(" update t_payment set cardStatus =");
		sql.append(status);
		sql.append(" where userId =");
		sql.append(userId);
		int result = executeUpdateSql(sql.toString());
		logger.info("ChangeAllCardStatus  effect={},status={},userId={}",result,status,userId);
	}
}
